import React from "react"
import List from './List'
import InputItem from './InputItem'

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      list: [
        {
          id: 1,
          title: '标题1',
          completed: false
        },
        {
          id: 2,
          title: '标题2',
          completed: false
        },
        {
          id: 3,
          title: '标题3',
          completed: false
        }
      ]
    }
  }

  render() {
    return (
      <div>
        <InputItem addItem={this.addList}></InputItem>
        <List list={this.state.list} 
              handleDelete={this.handleDelete}
              toggleCompleted={this.toggleCompleted}
              ></List>
      </div>
    )
  }

  toggleCompleted = (id) => {
    this.setState({
      list: this.state.list.map(item => {
        const completed = item.id === id ? 
                          !item.completed : 
                          item.completed
        return {
          ...item,
          completed
        }
      })
    })
  }

  handleDelete = (id) => {
    this.setState({
      list: this.state.list.filter(item => {
        return item.id !== id
      })
    })
  }

  addList = (title) => {
    this.setState({
      list: [...this.state.list, {id: `id-${Date.now()}`,title, completed: false}]
    })
  }

}

export default App
